package com.xiao.sulinges.controller;

import com.xiao.sulinges.service.ProductEsService;
import com.xiao.sulinges.vo.Commodity02Vo;
import com.xiao.sulinges.vo.CommodityVo;
import com.xiao.sulingpublic.to.ClassifyEsTo;
import com.xiao.sulingpublic.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author: 1322127758@qq.com
 * @date: 2022/3/20 10:30
 * @作用:
 */
@RequestMapping("/es/product")
@RestController
public class ProductEsController {

    @Autowired
    private ProductEsService productEsService;

    /**
     * 查询全部
     */
    @PostMapping("/list")
    public R list(@RequestBody ClassifyEsTo classifyEsTo) throws IOException {
        /**
         * 商品所属分类Id
         */
        final Integer[] clId = {null};

        List<CommodityVo> list = productEsService.list(classifyEsTo);
        /* 重新封装一下数据 主要加一个字段,前端用于点击分类时自动滚动到指定位置*/
        List<Commodity02Vo> collect = list.stream().map(ite -> {
            Commodity02Vo commodity02Vo = new Commodity02Vo();
            BeanUtils.copyProperties(ite, commodity02Vo);
            //判断分类id是否和上一个一样
            if (Objects.equals(clId[0], ite.getClId())) {
            } else {
                clId[0] = ite.getClId();
                commodity02Vo.setViewId(ite.getClId().toString());
            }
            return commodity02Vo;
        }).collect(Collectors.toList());

        return R.ok().put("commodityVos",collect);
    }

    /**
     * 将商品数据保存到es中
     * @param commodityVo
     * @return
     */
    @PostMapping("/save")
    public R save(@RequestBody CommodityVo commodityVo) throws IOException {
        if(null != commodityVo){
            productEsService.save(commodityVo);
            return R.ok("保存成功!");
        }
        return R.error("保存错误!");
    }

    /**
     * 删除商品数据
     */
    @RequestMapping("/delete")
    public R delete(@RequestParam("coId") Long coId) throws IOException {
        return productEsService.delete(coId);
    }

    /**
     * 修改数据
     */
    @RequestMapping("/update")
    public R update(@RequestBody CommodityVo commodityVo) throws IOException {
        return productEsService.update(commodityVo);
    }

}
